﻿using System;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Mvc4Demo.Core
{
    public static class KnockoutExtensions
    {
        private const string MvvmPrototye = "<script type=\"text/javascript\">\n function MvcViewModel() {0}\n {1} \n {2}\n {3} </script>";
        private const string MvvmProperty = "\n\t this.{0} = ko.observable(\"{1}\");";
        private const string MvvmApplyScript = "\nko.applyBindings(new MvcViewModel());";

        public static MvcHtmlString KoGenerateViewModel<TModel>(this HtmlHelper<TModel> htmlHelper)
        {
            if (htmlHelper.ViewData.Model != null)
            {
                var properties = new StringBuilder();

                foreach (var property in htmlHelper.ViewData.ModelMetadata.Properties)
                {
                    properties.Append(string.Format(MvvmProperty, property.PropertyName, property.Model));
                }

                return new MvcHtmlString(string.Format(MvvmPrototye, '{', properties, MvvmApplyScript, '}'));
            }

            return new MvcHtmlString("");
        }

        private const string MvvmInputBind = " data-bind=\"value : {0}\" />";

        public static MvcHtmlString KoTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
                                                                  Expression<Func<TModel, TProperty>> expression)
        {

            var mvcString = htmlHelper.TextBoxFor(expression).ToHtmlString();

            //ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            string expressionText = ExpressionHelper.GetExpressionText(expression);

            return new MvcHtmlString(mvcString.Replace("/>", string.Format(MvvmInputBind, expressionText)));
        }
    }
}